package com.foreknow.elm.dao.impl;

import com.foreknow.elm.dao.UserDao;
import com.foreknow.elm.po.Business;
import com.foreknow.elm.po.User;
import com.foreknow.elm.util.DBUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

/**
 * @author 啊滨
 * @date 2023/2/14 9:49
 */
public class UserDaoImpl implements UserDao {
    private Connection  con;
    private PreparedStatement pst;
    private ResultSet rs;
    @Override
    public User getUserByIdByPass(String userId, String password)throws Exception {
        String sql="SELECT * FROM user WHERE userId=? AND password=?";
        try {
        con = DBUtil.getConnection();
        pst = con.prepareStatement(sql);
        pst.setString(1,userId);
        pst.setString(2,password);
        rs=pst.executeQuery();
        while (rs.next()){
            User user=new User();
            user.setUserId(rs.getString("userId"));
            user.setPassword(rs.getString("password"));
            user.setUserName(rs.getString("userName"));
            user.setUserSex(rs.getInt("userSex"));
            user.setUserImg(rs.getString("userImg"));
            user.setDelTag(rs.getInt("delTag"));
            return user;
        }
        } finally {    //这里不能处理异常，也就是没有catch，只有finally
            DBUtil.close(rs, pst);  //这里负责关闭PreparedStatement和ResultSet
        }
        return null;
    }

    @Override
    public int getUserById(String userId) throws Exception {
        int count=0;
        String sql="SELECT COUNT(*) FROM user WHERE userId=?";
        try {
            con=DBUtil.getConnection();
            pst=con.prepareStatement(sql);
            pst.setString(1,userId);
            rs=pst.executeQuery();
            while (rs.next()){
              count=rs.getInt("count(*)");
            }
        } finally {    //这里不能处理异常，也就是没有catch，只有finally
            DBUtil.close(rs, pst);  //这里负责关闭PreparedStatement和ResultSet
        }
        return count;
    }

    @Override
    public int saveUser(String userId,String password,String userName,Integer userSex) throws Exception {
        int isRight=0;
        String sql="insert into user values(?,?,?,?,null,1)";
        try {
        con= DBUtil.getConnection();
        pst= con.prepareStatement(sql);
        pst.setString(1,userId);
        pst.setString(2, password);
        pst.setString(3, userName);
        pst.setInt(4, userSex);
        isRight=pst.executeUpdate();
    } finally {    //这里不能处理异常，也就是没有catch，只有finally
        DBUtil.close(rs, pst);  //这里负责关闭PreparedStatement和ResultSet
    }
        return isRight;
    }

}
